#include <sstream>

#include "SSLWrapper.hpp"
#include "ListenSocket.hpp"
#include "Logger.hpp"
#include "ConnectionHandlerRelay.hpp"

int protected_main(int argc, char **argv) {
	
	if (argc != 6) {
		std::cerr << "Syntax:" << std::endl;
		std::cerr << argv[0] << " <LOCAL-PORT> <REMOTE-IP> <REMOTE-PORT> <CERTIFICATE> <PRIVATE-KEY>" << std::endl;
		exit(1);
	}

	//initialize SSL
	SSL_CTX* context = SSLWrapper::init();
	
	//configure it
	SSLWrapper::setVerifyMode(context, SSL_VERIFY_NONE);
	SSLWrapper::loadCertificate(context, std::string(argv[4]));
	SSLWrapper::loadPrivatekey(context, std::string(argv[5]));

	ListenSocket socket = ListenSocket(IP("127.0.0.1"), atoi(argv[1]));
	int count = 0;
	while (true) {
		ConnectionHandler* newConn = new ConnectionHandlerRelay(context, IP(argv[2]), atoi(argv[3]), count++);
		socket.handleConnection(newConn);
		Logger::log(Logger::INFO, "Host connected to server.");
	}
	
	return 0;
}

int main(int argc, char **argv) {
//	return protected_main(argc, argv);
	
	try {
		return protected_main(argc, argv);
	} catch (const GenericException &E) {
		E.terminate();
	}
	return 1;
}
